<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="500px"
  >
    <BasicForm @register="registerForm">
      <template #fileid="{ model, field }">
        <a-upload
          name="file"
          :maxCount="1"
          accept=".pdf"
          :custom-request="upload"
          @remove="removeFile"
          :showUploadList="false"
        >
          <a-button type="primary">
            <UploadOutlined />
            上传pdf文件
          </a-button>
          <a
            style="width: 100%; display: block"
            v-if="fileId && fileId != 0"
            :href="uploadUrl + getPdfFileApi + fileId"
            target="_blank"
            >{{ uploadUrl + getPdfFileApi + fileId }}</a
          >
        </a-upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getDangerDb, addDangerDb, updateDangerDb } from '/@/api/ehs/templateHazard';
  import { addOrUpdateTemplateHazardSchema } from './templateHazard.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { uploadApi } from '/@/api/platform/upload';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getPdfFileApi } from '/@/api/platform/file';
  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'AddOrUpdateTemplateHazard',
    components: { BasicModal, BasicForm, UploadOutlined },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { uploadUrl } = useGlobSetting();
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const fileId = ref(null);
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: addOrUpdateTemplateHazardSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        fileId.value = null;
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
        }
        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });
        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (operateType.value == OperationTypeEnum.EDIT) {
          getTemplateHazardById();
          updateSchema({
            field: 'hdbcd',
            componentProps: { disabled: true },
          });
        } else {
          updateSchema({
            field: 'hdbcd',
            componentProps: { disabled: false },
          });
        }
      });

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      async function getTemplateHazardById() {
        getDangerDb(dataId.value)
          .then((res) => {
            console.log('res', res);
            fileId.value = res.fileid && res.fileid !== 0 ? res.fileid : null;
            setFieldsValue({
              ...res,
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function upload(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是excel文件则上传,否则提示文件格式错误
        if (fileType === 'pdf') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                fileId.value = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
              } else {
                fileId.value = undefined;
                createMessage.error('上传失败,请稍后重试');
              }
            })
            .catch((err) => {
              fileId.value = undefined;
              createMessage.error('上传失败,请稍后重试');
            });
        } else if (fileType !== 'pdf') {
          fileId.value = undefined;
          createMessage.error('文件格式不符,请上传pdf文件');
        }
      }
      function removeFile() {
        // 移除上传的文件,清空文件数据
        fileId.value = null;
      }
      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addDangerDb({ ...values, fileid: fileId.value })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateDangerDb({ ...values, fileid: fileId.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
              // createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      return {
        operateType,
        displayModuleTitle,
        registerModal,
        registerForm,
        getTemplateHazardById,
        onButtonOkClick,
        opSuccess,
        upload,
        removeFile,
        fileId,
        uploadUrl,
        getPdfFileApi,
      };
    },
  });
</script>

<style scoped></style>
